package cn.iocoder.yudao.module.trade.config.controller.app;

import cn.hutool.core.util.ObjUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.api.shop.info.ShopInfoApi;
import cn.iocoder.yudao.module.trade.config.dal.dataobject.TradeConfigDO;
import cn.iocoder.yudao.module.trade.config.service.TradeConfigService;
import cn.iocoder.yudao.module.trade.config.vo.AppTradeConfigRespVO;
import cn.iocoder.yudao.module.trade.config.vo.TradeConfigSaveReqVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 App - 交易配置")
@RestController
@RequestMapping("/trade/config")
@RequiredArgsConstructor
@Validated
@Slf4j
public class AppTradeConfigController {

    @Resource
    private TradeConfigService tradeConfigService;

    @Resource
    private ShopInfoApi shopInfoApi;

    @PutMapping("/save")
    @Operation(summary = "更新交易配置")
    @PreAuthorize("@mm.isMerchant()")
    public CommonResult<Boolean> updateConfig(@Valid @RequestBody TradeConfigSaveReqVO updateReqVO) {
        Long userId = getLoginUserId();
        Long shopId = shopInfoApi.getShopIdByMemberUserId(userId);
        tradeConfigService.saveTradeConfig(shopId, updateReqVO);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得交易配置", description = "如预设的退款理由及退货理由")
    @PermitAll
    public CommonResult<AppTradeConfigRespVO> getTradeConfig(@RequestParam(value = "shopId", required = false) Long shopId) {
        if (shopId == null || shopId <= 0) {
            Long userId = getLoginUserId();
            shopId = shopInfoApi.getShopIdByMemberUserId(userId);
        }
        if (shopId == null || shopId <= 0) {
            return success(new AppTradeConfigRespVO());
        }
        TradeConfigDO config = ObjUtil.defaultIfNull(tradeConfigService.getOrCreateTradeConfigByShopId(shopId), new TradeConfigDO());
        AppTradeConfigRespVO respVO = BeanUtils.toBean(config, AppTradeConfigRespVO.class);
        return success(respVO);
    }

}
